"use strict";

var C = require('../common');

module.exports = function (webModule, route, options, cb) {

    options || (options = {});
    options.key || (options.key = 'nf.sid');

    cb(null, function (req, res, next) {
        if (!req.session) {
            throw new C.Error.UsageError('Session middleware should be enabled before using form-session.');
        }

        req.tokenSessionKey = options.key;

        var token = req.body[options.key];
        if (!token) {
            token = req.query[options.key];
        }

        if (token) {
            var sid = C.H.popObject(token);
            if (!sid) {
                // Session expired
                return next();
            }

            if (sid === req.sessionID) {
                C.H.syslog('info', 'Session and token matched, token-session will be disabled.');
                return next();
            }

            //Reload session
            return req.sessionStore.get(sid, function(err, sess){
                if (err) {
                    C.H.syslog('error', 'Error occurred while getting session data from session store.', err);
                    next();
                } else if (!sess) {
                    C.H.syslog('warn', 'Session not found with valid token.');
                    next();
                } else {
                    C.H.syslog('info', 'Session overrided by token-session.');
                    req.sessionStore.createSession(req, sess);
                    req.sessionToken = C.H.cacheObject(req.sessionID);
                    next();
                }
            });
        } else {
            req.sessionToken = C.H.cacheObject(req.sessionID);
        }

        next();
    });
};